import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// 首页
import Layout from '@/views/layout'
import Home from '@/views/layout/home'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'
import Category from '@/views/layout/category'

const Login = () => import('@/views/login')
const Myorder = () => import('@/views/myorder')
const Pay = () => import('@/views/pay')
const Prodetail = () => import('@/views/prodetail')
const Search = () => import('@/views/search')
const SearchLists = () => import('@/views/search/lists.vue')
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    // 重定向
    redirect: '/home',
    // 二级路由配置
    children: [
      { path: '/home', component: Home },
      { path: '/cart', component: Cart },
      { path: '/user', component: User },
      { path: '/category', component: Category }
    ]
  },
  { path: '/login', component: Login },
  { path: '/myorder', component: Myorder },
  { path: '/pay', component: Pay },
  { path: '/search', component: Search },
  { path: '/searchLists', component: SearchLists },
  // 动态路由传参，确定将来在哪个商品，路由参数中需要携带 id
  { path: '/prodetail/:id', component: Prodetail }
]

const router = new VueRouter({
  routes
})

/**  所有的路由在真正被访问到之前(解析渲染对应组件页面前)，都会先经过全局前置守卫
* 只有全局前置守卫放行了，才会到达对应的页面
*
* 全局前置导航守卫
* to:到哪里去，到哪去的完整路由信息对象（路径，参数)
* from:从哪里来，从哪来的完整路由信息对象（路径，参数)
* next():是否放行
*    (1) next()直接放行，放行到to要去的路径
*    (2) next(路径)进行拦截，拦截到next里面配置的路径
*/

// 定义一个数组，专门存放所有权限访问的页面
const althUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  // 看 to.path 是否在 althUrls 中
  if (!althUrls.includes(to.path)) {
    return next()
  }
  // 是权限页面，需要判断 token
  const token = store.getters.getToken
  // console.log(token)
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
